package org.ykh.service.config;

import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.ykh.service.property.RedissonProperties;


/**
 * @author ykh
 */
@Configuration
@ConditionalOnClass({Redisson.class,RedisProperties.class})
public class RedissonConfig {


    private RedissonProperties redissonProperties;

    private RedisProperties redisProperties;

    public RedissonConfig(RedissonProperties redissonProperties, RedisProperties redisProperties) {
        this.redissonProperties = redissonProperties;
        this.redisProperties = redisProperties;
    }

    private final static String ADDRESS_PREFIX = "redis://";

    /**
     * 自动装配
     *
     */
    @Bean
    public RedissonClient redissonSingle() {
        Config config = new Config();
        if(StringUtils.isEmpty(redisProperties.getHost())){
            throw new RuntimeException("host is  empty");
        }
        SingleServerConfig serverConfig = config.useSingleServer()
                //redis://127.0.0.1:7181
                .setAddress(ADDRESS_PREFIX + redisProperties.getHost() + ":" + redisProperties.getPort())
                .setPingConnectionInterval(redissonProperties.getPingConnectionInterval())
                .setConnectionPoolSize(redissonProperties.getConnectionPoolSize())
                .setConnectionMinimumIdleSize(redissonProperties.getConnectionMinimumIdleSize())
                ;
        if(!StringUtils.isEmpty(redisProperties.getPassword())) {
            serverConfig.setPassword(redisProperties.getPassword());
        }
        // RedissonClient redisson = Redisson.create(config);
        return Redisson.create(config);
    }

}
